from flask import Blueprint, request, session
from app import db
from .models import Device
from UserManager.models import User
from AuthComponent import auth_required
from utils import respond, ERRORCODES
from flask import Blueprint, request, jsonify
from config import Config
from DataManager.models import Data

bp = Blueprint("DeviceManager", __name__, url_prefix="/device/")


@auth_required()
@bp.route("/list", methods=["GET"])
def list_devices():
    # 获取当前登录用户
    if "user_id" not in session:
        return respond(data=None, message="未登录", error_code=ERRORCODES.UNAUTHORIZED)

    user = User.query.filter_by(uuid=session["user_id"]).first()
    if not user:
        return respond(None, "用户未找到。", ERRORCODES.UNAUTHORIZED)

    try:
        # 查询用户绑定的设备
        devices = user.devices

        # 格式化设备数据
        device_list = [
            {"device_id": device.id, "name": device.name, "status": device.status}
            for device in devices
        ]
        return respond({"devices": device_list})

    except Exception as e:
        return respond(
            None, f"获取设备列表时发生错误: {str(e)}", ERRORCODES.INTERNAL_SERVER_ERROR
        )


@auth_required()
@bp.route("/query", methods=["GET"])
def inquire_device_status():
    device_id = request.args.get("device_id")
    if not device_id:
        return respond(None, "请求有误 device_id。", ERRORCODES.INVALID_DATA_FORMAT)

    try:
        device = Device.query.filter_by(id=device_id).first()
        if not device:
            return respond(None, "禁止访问", ERRORCODES.FORBIDDEN)

        status = device.status if hasattr(device, "status") else "未知状态"
        return respond({"device_id": device_id, "status": status})

    except Exception as e:
        return respond(None, f"没有权限: {str(e)}", error_code=ERRORCODES.UNAUTHORIZED)


@auth_required()
@bp.route("/bind", methods=["POST"])
def bind_device_to_user():
    data = request.get_json()
    device_id = data.get("device_id")
    if not device_id:
        return respond(None, "缺少必要参数 device_id。", ERRORCODES.MISSING_PARAMETERS)

    try:
        device = Device.query.filter_by(id=device_id).first()
        if not device:
            return respond(None, "设备记录不存在。", ERRORCODES.DEVICE_NOT_FOUND)

        device.owner = session["user_id"]
        db.session.commit()
        return respond({"message": "设备绑定用户成功。"})

    except KeyError as e:
        return respond(None, "未登录。", ERRORCODES.UNAUTHORIZED)

    except Exception as e:
        db.session.rollback()
        return respond(
            None, f"设备绑定用户时发生错误: {str(e)}", ERRORCODES.INTERNAL_SERVER_ERROR
        )


@auth_required()
@bp.route("/history", methods=["GET"])
def query_device_history():
    device_id = request.args.get("device_id")
    start_time = request.args.get("start_time")
    end_time = request.args.get("end_time")
    
    if not all([device_id, start_time, end_time]):
        return respond(None, "缺少必要参数: device_id/start_time/end_time", ERRORCODES.MISSING_PARAMETERS)

    try:
        # 验证设备归属
        device = Device.query.filter_by(id=device_id, owner=session["user_id"]).first()
        if not device:
            return respond(None, "设备不存在或无权访问", ERRORCODES.FORBIDDEN)

        # 查询历史数据
        history_data = Data.query.filter(
            Data.device_id == device_id,
            Data.timestamp.between(start_time, end_time)
        ).order_by(Data.timestamp.asc()).all()

        # 格式化响应
        formatted_data = [{
            "timestamp": data.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
            "temperature": data.avg_temperature,
            "humidity": data.avg_humidity,
            "pm2_5": data.avg_pm2_5,
            "ozone": data.avg_ozone,
            "nitro_dio": data.avg_nitro_dio,
            "methanal": data.avg_methanal,
            "carb_momo": data.avg_carb_momo,
            "bacteria": data.avg_bacteria,
            "radon": data.avg_radon,
            "fresh_air": data.avg_fresh_air
        } for data in history_data]

        return respond({"history": formatted_data})

    except Exception as e:
        return respond(
            None, f"历史数据查询失败: {str(e)}", ERRORCODES.INTERNAL_SERVER_ERROR
        )



